import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 登录页面
    {
      path: '/',
      name: 'login',
      component: () => import('../views/Login/Login.vue'),
    },
    // 主页
    {
      path: '/adminview',
      name: 'adminview',

      component: () => import('../views/AdminView/AdminView.vue'),
    },
    {
      path: '/trafficview',
      name: 'trafficview',

      component: () => import('../views/TrafficView/TrafficView.vue'),
    },
    {
      path: '/commonview',
      name: 'commonview',
      component: () => import('../views/CommonView/CommonView.vue'),
    },
  ],
})

// 设置主页导航守卫
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')
  // 判断是否有权限
  // 若有权限，next（）放行，若无权限，定向到login next（'/login'）
  if (to.path !== '/') {
    if (token) {
      let user_type = localStorage.getItem('user_type')
      if (user_type == 2) {
        next()
      } else if (user_type == 1) {
        if (to.path == '/adminview') {
          ElMessage({
            type: 'warning',
            message: '您没有足够的权限',
            showClose: true,
            duration: 2000,
          })
          next('/trafficview')
        }
      } else {
        if (to.path == '/adminview' || '/trafficview') {
          ElMessage({
            type: 'warning',
            message: '您没有足够的权限',
            showClose: true,
            duration: 2000,
          })
          next('/commonview')
        }
      }
      next()
    } else {
      ElMessage({
        type: 'error',
        message: '请先登录',
        showClose: true,
        duration: 2000,
      })
      next('/')
    }
  } else {
    next()
  }
})

export default router
